const { login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");
const { set } = require("../db/redis");
/**
 * 用户路由
 * @param {*} req
 * @returns { SuccessModel | ErrorModel | undefined }
 */
const handleUserRouter = (req) => {
  const method = req.method;
  // 登录
  if (method === "POST" && req.path === "/api/user/login") {
    const { username, password } = req.body;
    // const { username, password } = req.query;
    const result = login(username, password);
    return result.then((data) => {
      if (data.username) {
        // 设置 redis session
        req.session.username = data.username;
        req.session.realname = data.realname;
        set(req.sessionId, req.session); // 同步 redis
        return new SuccessModel();
      }
      return new ErrorModel("登录失败，账号或密码错误");
    });
  }
};
module.exports = handleUserRouter;
